<?php
/**
* phpCan - http://idc.anavallasuiza.com/
*
* phpCan is released under the GNU Affero GPL version 3
*
* More information at license.txt
*/

namespace data\formats;

defined('ANS') or die();

class Date extends Formats implements iFormats {
	var $format = 'date';

	protected function validDate ($date, $format = 'Y-m-d') {
		if ($date == '0000-00-00') {
			return $date;
		}

		if (!$date || preg_match('/^[0-9]+$/', $date)) {
			$new_date = intval($date);
		} else if (is_string($date) && !($new_date = strtotime($date))) {
			return false;
		}

		$date = date($format, $new_date);

		if ($new_date == 0) {
			$date = preg_replace('/[0-9]/', '0', $date);
		}

		return $date;
	}

	public function check ($value) {
		$this->error = array();

		if (!($value = $this->validDate($value['']))) {
			$this->error[''] = __('The value is not a valid date.');

			return false;
		}

		if (($value == '0000-00-00') && $this->settings['']['required']) {
			$this->error[''] = __('This field can not be empty');

			return false;
		}

		return true;
	}

	public function valueDB (\data\Data $Data, $value, $language = '', $id = 0) {
		return array(
			'' => $this->validDate($value[''])
		);
	}

	public function valueForm ($value) {
		return array(
			'' => $this->validDate($value[''], $this->settings['']['date_format'])
		);
	}

	public function valueHtml ($value) {
		return array(
			'' => $this->validDate($value[''], $this->settings['']['date_format'])
		);
	}

	public function settings ($settings) {
		$this->settings = $this->setSettings($settings, array(
			'' => array(
				'db_type' => 'date',

				'date_format' => 'd-m-Y',
				'default' => '0000-00-00',
			)
		));

		$this->settings['']['db_default'] = '0000-00-00';

		return $this->settings;
	}
}
?>
